/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.CustomPartDTO;
import org.springblade.modules.admin.dto.CustomPartsLogDTO;
import org.springblade.modules.admin.dto.WebCustomPartsLogDTO;
import org.springblade.modules.admin.entity.CustomPartsLog;
import org.springblade.modules.admin.entity.MaintainParts;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.CustomPartsLogEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.MaintainPartsService;
import org.springblade.modules.admin.mapper.CustomPartsLogMapper;
import org.springblade.modules.admin.service.ICustomPartsLogService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 自定义部件log 服务实现类
 *
 * @author ysq
 * @since 2024-01-02
 */
@Service
public class CustomPartsLogServiceImpl extends BaseServiceImpl<CustomPartsLogMapper, CustomPartsLog> implements ICustomPartsLogService {

	@Autowired
	private IMaintainPlanContentService maintainPlanContentService;

	@Autowired
	private IUserService userService;

	@Autowired
	private ITenantService tenantService;

	@Autowired
	private MaintainPartsService maintainPartsService;

	@Override
	public boolean addLog(CustomPartsLogDTO customPartsLogDTO) {
		// 0. 数据校验、相关实体类准备
		if (Func.isNull(customPartsLogDTO)) {
			throw new ServiceException("Param missing");
		}
		Long currentPlanId = customPartsLogDTO.getCurrentPlanId();
		Long closestPartId = customPartsLogDTO.getClosestPartId();
		String customPartName = customPartsLogDTO.getCustomPartName();
		if (Func.isNull(currentPlanId) || Func.isNull(closestPartId)) {
			throw new ServiceException("Param missing");
		}
		CustomPartsLog target = new CustomPartsLog();
		target.setPlanId(currentPlanId);
		CustomPartDTO customPartDTO = new CustomPartDTO();
		WebCustomPartsLogDTO webCustomPartsLogDTO = new WebCustomPartsLogDTO();
		String tenantId = AuthUtil.getTenantId();
		// 1. 数据封装
		// 1.1. 查询并封装webCustomPartsLogDTO 所描述的当前工单的信息
		webCustomPartsLogDTO.setCurrentPlanId(currentPlanId);
		// 工单信息
		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(currentPlanId);
		if (Func.isNull(maintainPlanContent)) {
			throw new ServiceException("No such plan");
		}
		webCustomPartsLogDTO.setTypeStatus(maintainPlanContent.getTypeStatus());
		// 具体位置
		webCustomPartsLogDTO.setFromLocation(customPartsLogDTO.getFromLocation());
		// 用户、租户信息
		Long userId = AuthUtil.getUserId();
		User user = userService.getById(userId);
		if (Func.isNull(user)) {
			throw new ServiceException("No such user");
		}
		webCustomPartsLogDTO.setUserName(user.getRealName());
		webCustomPartsLogDTO.setUserPhone(user.getPhone());
		Tenant tenant = tenantService.getOne(new LambdaQueryWrapper<Tenant>()
			.eq(Tenant::getTenantId, tenantId));
		if (Func.isNull(tenant)) {
			throw new ServiceException("No such tenant");
		}
		webCustomPartsLogDTO.setTenantName(tenant.getTenantName());
		// 将webCustomPartsLogDTO转换为json字符串
		String planMessage = Func.toJson(webCustomPartsLogDTO);
		target.setPlanMessage(planMessage);
		// 1.2. 查询并封装customPartDTO 所描述的自定义配件的信息
		MaintainParts maintainParts = maintainPartsService.getById(closestPartId);
		if (Func.isNull(maintainParts)) {
			throw new ServiceException("No such maintainParts");
		}
		customPartDTO.setCustomPartName(customPartName);
		String ancestors = maintainParts.getAncestors();
		// 1.2.1. 通过ancestors查询所有的祖先节点
		String[] ancestorIds = ancestors.split(",");
		StringBuilder customPartPath = new StringBuilder();
		for (String ancestorId : ancestorIds) {
			// 当id 为0 时，则为最上级节点
			if (!Func.equals(ancestorId, "0")) {
				MaintainParts ancestor = maintainPartsService.getById(ancestorId);
				if (Func.isNull(ancestor)) {
					throw new ServiceException("No such ancestor");
				}
				customPartPath.append(ancestor.getName()).append("> ");
			}
		}
		customPartPath.append(maintainParts.getName());
		customPartPath.append("- ").append(customPartName);
		customPartDTO.setCustomPartPath(customPartPath.toString());
		// 将customPartDTO转换为json字符串
		String records = Func.toJson(customPartDTO);
		target.setRecords(records);
		target.setStatus(CustomPartsLogEnum.MAINTAIN_ADMIN_LOG.getType());
		return this.save(target);
	}

}
